<?php

namespace App\Http\Middleware;

use App\Http\Controllers\Api\LoginController;
use App\Http\Server\LoginServer;
use App\Http\Services\RedisAuthService;
use App\Services\JsonResponseService;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;

class AppAuthMiddleware
{
    /**
     * 小程序验证登录中间件
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        // 从请求头中获取令牌
        $token = $request->header('token')??$request->input('token');
        $redisServerce = new LoginServer();

        if (!$token) {
            return JsonResponseService::error('未提供token令牌','201','');
            //return response()->json(['code'=>0,'message' => '未提供token令牌']);
        }


        // 从 Redis 中获取用户 ID
        $data = LoginServer::getUserInfoForToken($token);
        //$data = $redisServerce->getUserInfoByToken($token);

        if (empty($data)) {
            return response()->json(['message' => '无效的令牌','code'=>401]);
        }
        // 将用户 ID 存储到请求中，方便后续使用
        $request->offsetSet('user_id', $data['id']);
        return $next($request);
    }
}
